//
//  UIColor.swift
//  HuaYun
//
//  Created by enghou on 2018/6/27.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit

extension UIColor{
    
    static func hex(_ hexStr: String)->UIColor{
        
        var cString = hexStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
        
        if cString.hasPrefix("#"){
            
            let index   = cString.index(cString.startIndex, offsetBy: 1)
            cString     = String(cString.prefix(upTo: index))
        }
        
        if cString.count != 6 {
            return UIColor.red
        }
        
        let rIndex      = cString.index(cString.startIndex, offsetBy: 2)
        
        let rString     = cString.prefix(upTo: rIndex)
        
        let otherString = cString.suffix(from: rIndex)
        
        let gIndex      = otherString.index(otherString.startIndex, offsetBy: 2)
        
        let gString     = otherString.prefix(upTo: gIndex)
        
        let bIndex      = cString.index(cString.endIndex, offsetBy: -2)
        
        let bString     = cString.suffix(from: bIndex)
        
        var r:CUnsignedInt  = 0,g:CUnsignedInt = 0 ,b:CUnsignedInt = 0
        
        Scanner(string: String(rString)).scanHexInt32(&r)
        
        Scanner(string: String(gString)).scanHexInt32(&g)
        
        Scanner(string: String(bString)).scanHexInt32(&b)
        
        return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(1))
    }
    
}

extension UIColor{
    static var tableSeparator: UIColor{
        get{
            return UIColor.init(red: 0.783922, green: 0.780392, blue: 0.8, alpha: 1)
        }
    }
}

extension UIColor{
    
    
    func image(size: CGSize) -> UIImage {
        
        UIGraphicsBeginImageContext(size)
        
        if let context = UIGraphicsGetCurrentContext() {
            
            context.setFillColor(self.cgColor)
            
            context.fill(CGRect(origin: CGPoint.zero, size: size))
            
            if let image = context.makeImage() {
                
                return UIImage(cgImage: image)
                
            }
        }
        
        return UIImage()
        
    }
}
